﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model.Models;
using DFGK_WMS.WebAPI.Controllers.Result;
using DFGK_WMS.WebAPI.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NetTaste;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Drawing.Printing;
using System.Net.Mime;
using System.Security.Claims;
using System.Xml.Linq;

namespace DFGK_WMS.WebAPI.Controllers.基础数据
{
    /// <summary>
    /// 客户管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TCustomerController : ControllerBase
    {
        private readonly ILogRepository logRepository;
        private readonly ITCustomerRepository custR;

        public TCustomerController(ITCustomerRepository custR, ILogRepository logRepository)
        {
            this.custR = custR;
            this.logRepository = logRepository;
        }
        /// <summary>
        /// 查询客户
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetAllTCustomer(string? name, int pageIndex = 1, int pageSize = 5)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                BaseResult.Result("400", "分页条件有误！");
            }
            var res = custR.GetAllTCustomer(name, pageIndex, pageSize, out var totalCount);
            return Ok(BaseResult.Result(res, "200", totalCount));
        }
        /// <summary>
        /// 查询客户 下拉框专用
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCustomerSelect(string? name)
        {
            var res = custR.GetCustomerSelect(name).Select(s=>new { s.Id,s.Name });
            return Ok(BaseResult.Result(res, "200", 0));
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public FileContentResult ExportToExcel(string? name)
        {
            var list = custR.GetAllTCustomer(name, 1, int.MaxValue, out var totalCount);
            var keyValuePairs = new Dictionary<string, string>()
            {
                { "Name","客户名称" },
                { "Code","客户编码"},
                { "ResponsiblePerson","责任人"},
                { "Tel","电话"},
                { "MobilePhone","手机号"},
                {"Postcode","邮编" },
                {"Contact","联系人" },
                {"ContactMobile","联系人手机" },
                {"AddrDetail","地址" },
                {"Remark","备注" }
            };
            var exList = list.Select(s => new
            {
                s.Name,
                s.Code,
                s.ResponsiblePerson,
                s.Tel,
                s.MobilePhone,
                s.Postcode,
                s.Contact,
                s.ContactMobile,
                s.AddrDetail,
                s.Remark
            }).ToList();
            var fileBytes = Utils.ExportToExcel(exList, keyValuePairs);
            return File(fileBytes, MediaTypeNames.Application.Octet, "客户.xlsx");
        }
        /// <summary>
        /// 根据客户id查询客户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTCustomerById(int id)
        {
            if (id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var res = custR.GetCustomerById(id);
            return Ok(BaseResult.Result(res, "200"));
        }
        /// <summary>
        /// 查询客户类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTCustomerDic()
        {
            return Ok(BaseResult.Result(custR.GetTCustomerDic().Select(c => new { c.Id, c.ItemName }), "200"));
        }
        /// <summary>
        /// 添加客户
        /// </summary>
        /// <param name="Customer"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddTCustomer(TCustomer Customer)
        {
            var custOmerList = custR.GetAll().Where(s => s.Id != Customer.Id && s.Code == Customer.Code);
            if (custOmerList.Any())
            {
                return Ok(BaseResult.Result(false, "添加失败,编码重复", "500"));
            }

            var res = custR.AddTCustomer(Customer);
            if (res)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog
                {
                    LogType = 1,
                    ActionType = 4,
                    ModuleName = "基础数据",
                    UserName = uname,
                    RealName = runame,
                    UserId = uid,
                    Description = uname + "创建了客户" + Customer.Name,
                    //获取前端IP地址
                    Ipaddress = ip
                };

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "添加成功", "200"));
            }
            return Ok(BaseResult.Result(false, "添加失败", "500"));
        }
        /// <summary>
        /// 修改客户
        /// </summary>
        /// <param name="Customer"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdTCustomer(TCustomer Customer)
        {
            if (Customer.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            if (string.IsNullOrEmpty(Customer.Code))
            {
                return Ok(BaseResult.Result("400", "必填项不能为空！"));
            }
            var res = custR.UpdTCustomer(Customer);
            if (res)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 6;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = uid;
                logg.Description = uname + "修改了客户" + Customer.Name;
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "修改成功", "200"));
            }
            return Ok(BaseResult.Result(false, "修改失败", "500"));
        }
        /// <summary>
        /// 删除客户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelCustomer(int id)
        {
            if (id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var res = custR.DelTCustomer(id);
            if (res)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int rid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 5;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = rid;
                logg.Description = uname + "删除了客户";
                //获取前端IP地址
                logg.Ipaddress = ip;

                logRepository.AddTLod(logg);
                return Ok(BaseResult.Result(true, "删除成功", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败", "500"));
        }

        /// <summary>
        /// 批量删除客户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelCustomerList(int[] idList)
        {
            if (idList.Length <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            var daRes = true;
            foreach (var id in idList)
            {
                var res = custR.DelTCustomer(id);
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int rid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                TLog logg = new TLog();
                logg.LogType = 1;
                logg.ActionType = 5;
                logg.ModuleName = "基础数据";
                logg.UserName = uname;
                logg.RealName = runame;
                logg.UserId = rid;
                logg.Description = res ? uname + "删除了客户" : uname + "删除客户失败";
                //获取前端IP地址
                logg.Ipaddress = ip;
                logRepository.AddTLod(logg);
                if (!res)
                {
                    daRes = false;
                    break;
                }
            }
            if (daRes)
            {
                return Ok(BaseResult.Result(true, "删除成功", "200"));
            }
            return Ok(BaseResult.Result(false, "删除失败", "500"));
        }

        /// <summary>
        /// file
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadUserInfo(IFormFile file)
        {
            try
            {
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    return Ok(BaseResult.Result("400", "没有选择文件或文件为空"));
                }
                string message = "";
                var postFile = Request.Form.Files[0];
                string extName = Path.GetExtension(postFile.FileName);
                if (!new string[] { ".xls", ".xlsx" }.Contains(extName))
                {
                    return Ok(BaseResult.Result("400", "必须是Excel文件"));
                }
                string uname = HttpContext.User.FindFirstValue("UserName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                MemoryStream ms = new MemoryStream();
                postFile.CopyTo(ms);
                ms.Position = 0;
                IWorkbook wb = null;
                if (extName.ToLower().Equals(".xls")) // 97-2003版本
                {
                    wb = new HSSFWorkbook(ms);
                }

                else
                {
                    wb = new XSSFWorkbook(ms); // 2007以上版本
                }
                ISheet sheet = wb.GetSheetAt(0);
                //总行数（0开始）
                int totalRow = sheet.LastRowNum;
                // 总列数（1开始）
                int totalColumn = sheet.GetRow(0).LastCellNum;
                bool chongfu = false;
                bool dbchongfu = false;
                List<TCustomer> stuList = new();
                for (int i = 1; i <= totalRow; i++)
                {
                    IRow row = sheet.GetRow(i);
                    string? Code = row.GetCell(1)?.StringCellValue;
                    string? Shortname = row.GetCell(2)?.StringCellValue;
                    string? Name = row.GetCell(3)?.StringCellValue;
                    string? ResponsiblePerson = row.GetCell(4)?.StringCellValue;
                    string? Tel = "";
                    if (row.GetCell(5)?.CellType == CellType.String)
                    {
                        Tel = row.GetCell(5)?.StringCellValue;
                    }
                    else
                    {
                        Tel = row.GetCell(5)?.NumericCellValue.ToString();
                    }
                    string? MobilePhone = "";
                    if (row.GetCell(6)?.CellType == CellType.String)
                    {
                        MobilePhone = row.GetCell(6)?.StringCellValue;
                    }
                    else
                    {
                        MobilePhone = row.GetCell(6)?.NumericCellValue.ToString();
                    }
                    string? ContactMobile = "";
                    if (row.GetCell(7)?.CellType == CellType.String)
                    {
                        ContactMobile = row.GetCell(7)?.StringCellValue;
                    }
                    else
                    {
                        ContactMobile = row.GetCell(7)?.NumericCellValue.ToString();
                    }
                    int? MengNiuStatus = row.GetCell(10)?.StringCellValue == "是" ? 0 : 1;
                    int? MengNiuEmphasis = row.GetCell(11)?.StringCellValue == "是" ? 1 : 0;
                    string? Postcode = "";
                    if (row.GetCell(12)?.CellType == CellType.String)
                    {
                        Postcode = row.GetCell(12)?.StringCellValue;
                    }
                    else
                    {
                        Postcode = row.GetCell(12)?.NumericCellValue.ToString();
                    }
                    string? AddrDetail = row.GetCell(13)?.StringCellValue;
                    string? Remark = row.GetCell(14)?.StringCellValue;
                    if (string.IsNullOrEmpty(Code))
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(Name) && string.IsNullOrEmpty(Shortname))
                    {
                        continue;
                    }
                    //查询当前文件是否有重复的六九码
                    chongfu = stuList.Where(x => x.Code == Code).Any();
                    if (chongfu)
                    {
                        message += Code + "重复";
                        continue;
                    }
                    //查询库数据库中是否有重复的六九码
                    dbchongfu = custR.GetAll().Where(x => x.Code == Code).Any();
                    if (dbchongfu)
                    {
                        message += Code + "重复";
                        continue;
                    }
                    var customer = new TCustomer
                    {
                        Code = Code,
                        Shortname = Shortname,
                        Name = Name,
                        TypeId = 1,
                        TypeName = "优质客户",
                        DisplayOrder = 0,
                        ResponsiblePerson = ResponsiblePerson,
                        Tel = Tel == "0" ? "" : Tel,
                        MobilePhone = MobilePhone == "0" ? "" : MobilePhone,
                        ContactMobile = ContactMobile == "0" ? "" : ContactMobile,
                        MengNiuStatus = MengNiuStatus == 1 ? true : false,
                        MengNiuEmphasis = MengNiuEmphasis == 1 ? true : false,
                        Postcode = Postcode,
                        AddrDetail = AddrDetail,
                        Remark = Remark,
                        CreateUserId = uid,
                        CreateUserName = uname,
                        CreateDate = DateTime.Now,
                    };
                    stuList.Add(customer);
                }
                if (stuList.Count <= 0)
                {
                    //message = "文件信息为空或别写字段为空！";
                    return Ok(BaseResult.Result(false, "导入失败！" + message, "500"));
                }
                bool result = custR.AddCustomerList(stuList);
                wb.Close();
                if (result)
                {
                    return Ok(BaseResult.Result(true, "导入成功！" + message, "200"));
                }
                return Ok(BaseResult.Result(false, "导入失败！", "500"));
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
